import { addTodo, deleteTodo, clearCheckToto, changeTodoDone, changeAllTodo } from "../constants/constants";

/*初始化的todoList数据*/
const initState = [
    { id: 1, name: "吃饭", done: true },
    { id: 2, name: "睡觉", done: true },
    { id: 3, name: "打豆豆", done: true },
]

export const reducer = (preState = initState, action) => {
    const { type, todoObject, id, done } = action
    switch (type) {
        case addTodo:
            return [todoObject, ...preState]
        case deleteTodo:
            return [...preState].filter(todo => todo.id !== id)
        case clearCheckToto:
            return [...preState].filter(todo => !todo.done)
        case changeTodoDone:
            const changeTodoDoneFunc = () => {
                const newInitState = [...preState]
                const currentTodo = newInitState.find(todo => todo.id === id).done = done
                return newInitState
            }
            return changeTodoDoneFunc()
        case changeAllTodo:
            const newInitState = [...preState]
            newInitState.forEach(todo => {
                todo.done = done
            })
            return newInitState
        default:
            return preState
    }
}
